package com.example.yk

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.yk.entity.BannerEntityResult
import com.example.yk.entity.GoodsEntityResult
import com.example.yk.entity.GroupEntityResult
import com.example.zk3.mvvm.BaseViewModel
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

class MainViewModel:BaseViewModel() {
    val groupSuccess = MutableLiveData<GroupEntityResult>()
    val groupFail = MutableLiveData<String>()

    fun group(){
        viewModelScope.launch {
            try {
                val result = apiServer.group()
                groupSuccess.value = result
            }catch (e:Exception){
                groupFail.value = e.message
            }
        }
    }
    val bannerSuccess = MutableLiveData<BannerEntityResult>()
    val bannerFail = MutableLiveData<String>()
    fun banner(adType:String){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,String>()
                map.put("adType",adType)
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),json)
                val result = apiServer.banner(body)
                bannerSuccess.value = result
            }catch (e:Exception){
                bannerFail.value = e.message
            }

        }
    }
    val goodsSuccess = MutableLiveData<GoodsEntityResult>()
    val goodsFail = MutableLiveData<String>()
    fun goods(){
        viewModelScope.launch {
            try {
                val map = mutableMapOf<String,Any>()
                map.put("isQueryGoods",true)
                map.put("size",4)
                map.put("type","c_home")
                val json = Gson().toJson(map)
                val body = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),json)
                val result = apiServer.goods(body)
                goodsSuccess.value = result
            }catch (e:Exception){
                goodsFail.value = e.message
            }
        }
    }
}